<?php
/**
 * Created by PhpStorm.
 * User: Kevin
 * Date: 2018/12/17
 * Time: 16:08
 */
namespace app\api\controller;
use think\Db;
class Couponshop extends Base
{
    /**
     * 异地登录验证
     * @return string|void
     */
    public function _initialize()
    {
        header('Access-Control-Allow-Origin:*');
        extract(input());
        $auth = $this->checkAll($user_id,$time,$value,$reqKey);
        if($auth == 112){
            echo json_encode(['status'=>301,'msg'=>$this->otherLogin]);
            exit;
        }elseif($auth == 110){
            echo json_encode(['status' => 302, 'msg' => $this->frost]);
            exit;
        }
    }
    
    /**
     * 商城首页(优惠券列表)
     */
    public function couponTwo(){
        extract(input());
        $this->couponDown();
        $today = date('Y-m-d H:i:s');
        $where = array();
        $where['coupon_status'] = 1;
        $where['coupon_end'] = array('>',$today);
        //1、列表
        $data = Db::table('up_coupon')
            ->where($where)
            ->order('coupon_status ASC,coupon_end DESC,coupon_get_num ASC,coupon_time DESC')
            ->page(1,4)
            ->field('coupon_id,coupon_name,coupon_image,coupon_num,coupon_price,coupon_get_num')
            ->select();
        if($data){
            foreach ($data as $k=>$v){
                $data[$k]['mc_status'] = '';
                $have = Db::table('up_my_coupon')
                    ->where('mc_coupon_id',$v['coupon_id'])
                    ->where('mc_user_id',$user_id)
                    ->find();
                if($have){
                    $data[$k]['mc_status'] = $have['mc_status'];
                }
            }
        }
        //1、列表
        $data2 = Db::table('up_shop_coupon')
            ->where($where)
            ->order('coupon_status ASC,coupon_end DESC,coupon_get_num ASC,coupon_time DESC')
            ->page(1,4)
            ->field('coupon_id,coupon_name,coupon_image,coupon_num,coupon_price,coupon_money,coupon_get_num')
            ->select();
        if($data2){
            foreach ($data2 as $k=>$v){
                $data2[$k]['mc_status'] = '';
                $have = Db::table('up_my_shop_coupon')
                    ->where('mc_coupon_id',$v['coupon_id'])
                    ->where('mc_user_id',$user_id)
                    ->find();
                if($have){
                    $data2[$k]['mc_status'] = $have['mc_status'];
                }
            }
        }
        return json(['status'=>200,'msg'=>$data,'shop'=>$data2]);
    }
    /**
     * 商铺商城首页(优惠券列表)
     */
    public function couponIndex(){
        extract(input());
        $today = date('Y-m-d H:i:s');
        $where = array();
        $where['coupon_status'] = 1;
        $where['coupon_end'] = array('>',$today);
        if(isset($keyword) && $keyword){
            $where['coupon_name'] = ['like','%' . $keyword . '%'];
            $order = 'coupon_status ASC,coupon_end DESC,coupon_get_num ASC,coupon_time DESC';
            $field = 'coupon_id,coupon_name,coupon_image,coupon_num,coupon_price,coupon_money,coupon_get_num';
        }else{
            if($type == 1){ //同城
                $where['s_qu'] = $qu;
                $order = 'coupon_status ASC,coupon_end DESC,coupon_get_num ASC,coupon_time DESC';
                $field = 'coupon_id,coupon_name,coupon_image,coupon_num,coupon_price,coupon_money,coupon_get_num';
            }elseif ($type == 3){ //所有
                $order = 'coupon_status ASC,coupon_end DESC,coupon_get_num ASC,coupon_time DESC';
                $field = 'coupon_id,coupon_name,coupon_image,coupon_num,coupon_price,coupon_money,coupon_get_num';
            }else{ //2是距离
                if(!isset($lat) || $lat == ''){
                    $lat = 0;
                }
                if(!isset($lon) || $lon == ''){
                    $lon = 0;
                }
                $field = 'coupon_id,coupon_name,coupon_image,coupon_num,coupon_price,coupon_money,coupon_get_num';
                $field .= ',ROUND(6378.138 * 2 * ASIN(SQRT(POW(SIN(('.$lat.'* PI() / 180 - s_lat * PI() / 180) / 2),2) + COS('.$lat.' * PI() / 180) * COS(s_lat * PI() / 180) * POW(SIN(('.$lon.' * PI() / 180 - s_lon * PI() / 180) / 2),2))) * 1000) AS distance';
                $order = 'distance ASC';
            }
        }

        $data2 = Db::table('up_shop_coupon')->alias('c')
            ->join('up_shops s','c.coupon_s_id=s.s_id','LEFT')
            ->where($where)
            ->order($order)
            ->page($page,12)
            ->field($field)
            ->select();
        if($data2){
            foreach ($data2 as $k=>$v){
                $data2[$k]['mc_status'] = '';
                $have = Db::table('up_my_shop_coupon')
                    ->where('mc_coupon_id',$v['coupon_id'])
                    ->where('mc_user_id',$user_id)
                    ->find();
                if($have){
                    $data2[$k]['mc_status'] = $have['mc_status'];
                }
            }
        }
        return json(['status'=>200,'msg'=>$data2]);
    }
    /**
     * 优惠券详情：
     */
    public function couponInfo(){
        extract(input());
        $where = array();
        $where['coupon_id'] = $coupon_id;
        //1、列表
        $data = Db::table('up_shop_coupon')->alias('c')
            ->join('up_shops s','c.coupon_s_id=s.s_id','LEFT')
            ->join('up_area a','s.s_sheng=a.district_id','LEFT')
            ->join('up_area a2','s.s_shi=a2.district_id','LEFT')
            ->join('up_area a3','s.s_qu=a3.district_id','LEFT')
            ->where($where)
            ->field('c.*,s.s_name,s.s_address,a.district sheng,a2.district shi,a3.district qu')
            ->find();
        $data['mc_status'] = '';
        $have = Db::table('up_my_shop_coupon')
            ->where('mc_coupon_id',$coupon_id)
            ->where('mc_user_id',$user_id)
            ->find();
        if($have){
            $data['mc_status'] = $have['mc_status'];
        }
        return json(['status'=>200,'msg'=>$data]);
    }
    /**
     * 兑换
     */
    public function couponGet(){
//        $user_id=34;$coupon_id=32;$coupon_s_id=18;
        extract(input());
        $where = array();
        $where['coupon_id'] = $coupon_id;
        $coupon = Db::table('up_shop_coupon')->where($where)->find();
        $user = Db::table('up_u_user')->where('user_id',$user_id)
            ->field('user_all_money,user_recharge,user_active_money')->find();
        $insert = [
            'mc_user_id'=>$user_id,
            'mc_coupon_id'=>$coupon_id
        ];
        $have = Db::table('up_my_shop_coupon')->where($insert)->find();
        if($have){
            return json(['status'=>0,'msg'=>'您已经领过了']);
        }
        if($coupon['coupon_get_num'] >= $coupon['coupon_num']){
            return json(['status'=>0,'msg'=>'已经兑换完了']);
        }
        if($coupon['coupon_status'] != 1){
            return json(['status'=>0,'msg'=>'已下架']);
        }
        $i_have = $user['user_all_money']+$user['user_recharge']+$user['user_active_money'];
        if($coupon['coupon_price'] > $i_have){
            return json(['status'=>0,'msg'=>'金币不足']);
        }
        $time = time();
        $num = substr(base_convert(md5(uniqid(md5(microtime(true)),true)), 16, 10), 0, 8);
        $insert['mc_number'] = time() . rand(100000,999999);
        $insert['mc_code'] = $this->getMyNum($num,$coupon_s_id);
        $insert['mc_s_id'] = $coupon_s_id;
        $insert['mc_over_date'] = date("Y-m-d",($time + 3600*24*$coupon['coupon_use_day']));
        $insert['mc_ercode'] = Qrcode("s_id=$coupon_s_id&coupon_id=$coupon_id&uid=$user_id",'');
        $insert['mc_date'] = date('Y-m-d');
        $insert['mc_time'] = date('Y-m-d H:i:s');
        Db::startTrans();
        try {
            Db::table('up_my_shop_coupon')->insert($insert);
            Db::table('up_shop_coupon')->where($where)->setInc('coupon_get_num');
            //扣钱了--start--
            $cp_price = $coupon['coupon_price'];
            if($user['user_recharge'] > 0){
                if($user['user_recharge'] >= $cp_price){
                    Db::table('up_u_user')->where('user_id',$user_id)->setDec('user_recharge',$cp_price);
                    $cp_price = 0;
                }else{
                    $cp_price = $cp_price - $user['user_recharge'];
                    Db::table('up_u_user')->where('user_id',$user_id)->setField('user_recharge',0);
                }
            }
            if($user['user_all_money'] > 0 && $cp_price > 0){
                if($user['user_all_money'] >= $cp_price){
                    Db::table('up_u_user')->where('user_id',$user_id)->setDec('user_all_money',$cp_price);
                    $cp_price = 0;
                }else{
                    $cp_price = $cp_price - $user['user_all_money'];
                    Db::table('up_u_user')->where('user_id',$user_id)->setField('user_all_money',0);
                }
            }
            if($user['user_active_money'] > 0 && $cp_price > 0){
                Db::table('up_u_user')->where('user_id',$user_id)->setDec('user_active_money',$cp_price);
            }
            //扣钱了-- end --
            //兑换成功就入明细
            allInDetail($user_id,2,'优惠券兑换',$coupon['coupon_price'],9);
            Db::commit();
            return json(['status'=>200,'msg'=>'OK']);
        } catch (\Exception $e) {
            Db::rollback();
            return json(['status'=>0,'msg'=>'领取失败']);
        }

    }
    /**
     * type：1待领取  2未使用  3已使用  4已过期
     * 我的优惠券（我的订单）：
     * mc_user_id是我的话，说明券是我的
     *              mc_send_status：1是正常（可以送人） 2是好友待接受  3是已接受  4已退还（可以送人）
     * mc_send_user_id是我的话，说明是别人送我的
     */
    public function myCoupon(){
        extract(input());
        $where = array();
        $where['mc_user_id'] = $user_id;
        //1、列表
        if ($type == 1){ //不管券有没有过期，只要有待领取的就去领取（定时器7天不领会返回）
            $where = [
                'mc_send_user_id' => $user_id,
                'mc_send_status' => 2,
            ];
            $data = Db::table('up_my_shop_coupon mc')
                ->join('up_shop_coupon c','mc.mc_coupon_id=c.coupon_id','LEFT')
                ->join('up_shops s','mc.mc_s_id=s.s_id','LEFT')
                ->where($where)
                ->order('mc_time DESC')
                ->field('mc_id,mc_user_id,mc_send_user_id,mc_number,mc_date,mc_over_date,mc_status,mc_send,mc_send_status,coupon_name,coupon_image,s_phone')
                ->page($page,15)
                ->select();

        }else{
            if($type == 2){ //只要是我的，不管有没有送人，只要是未使用的状态
                $where1 = [
                    'mc_user_id' => $user_id,
                    'mc_status' => 1,
                    'mc_send_status' => ['in','1,2,4'],
                ];
                $where2 = [ //只要是送我的，必须是已接受且未使用的
                    'mc_send_user_id' => $user_id,
                    'mc_status' => 1,
                    'mc_send_status' => 3
                ];
            }elseif ($type == 3){
                $where1 = [
                    'mc_user_id' => $user_id,
                    'mc_status' => 2,
                ];
                $where2 = [
                    'mc_send_user_id' => $user_id,
                    'mc_status' => 2,
                    'mc_send_status' => 3
                ];
            }else{
                $where1 = [
                    'mc_user_id' => $user_id,
                    'mc_status' => 3,
                ];
                $where2 = [
                    'mc_send_user_id' => $user_id,
                    'mc_status' => 3,
                    'mc_send_status' => 3
                ];
            }
            $data = Db::table('up_my_shop_coupon mc')
                ->join('up_shop_coupon c','mc.mc_coupon_id=c.coupon_id','LEFT')
                ->join('up_shops s','mc.mc_s_id=s.s_id','LEFT')
                ->where(function ($query) use($where1) {
                    $query->where($where1);
                })
                ->whereOr(function ($query) use($where2) {
                    $query->where($where2);
                })
                ->order('mc_time DESC')
                ->field('mc_id,mc_user_id,mc_send_user_id,mc_number,mc_date,mc_over_date,mc_status,mc_send,mc_send_status,coupon_name,coupon_image,s_phone')
                ->page($page,15)
                ->select();
        }
        return json(['status'=>200,'msg'=>$data,'type'=>$type]);
    }
    /**
     * 我的优惠券详情（我的进入的详情）：
     * mc_status：1未使用  2已使用  3已过期
     * mc_user_id是我的话，说明券是我的
     *              mc_send_status：1是正常（可以送人，联系商家） 2是待接受（没有操作） 3是已接受（没有操作） 4已退还（可以送人，联系商家）
     *              （mc_send_status为2.3的情况下看不到二维码，如果要展示送给谁了，取带2的用户信息）
     * mc_send_user_id是我的话，说明是别人送我的
     *              mc_send_status：2是待接受（可以接受，看不到二维码）  3是已接受（可以联系商家，看到二维码）
     *              （如果要展示是谁送给我的，取不带2的用户信息）
     */
    public function myCouponInfo(){
        extract(input());
        $where = array();
        $where['mc_id'] = $mc_id;
        //1、列表
        $field = 'mc.*,coupon_name,coupon_image,coupon_money,s_name,s_phone,s_address,a.district sheng,a2.district shi,a3.district qu';
        $field .= ',u.user_username,u.user_phone,u2.user_username user_username2,u2.user_phone user_phone2,coupon_use_day';
        $data = Db::table('up_my_shop_coupon mc')
            ->join('up_shop_coupon c','mc.mc_coupon_id=c.coupon_id','LEFT')
            ->join('up_u_user u','mc.mc_user_id=u.user_id','LEFT')
            ->join('up_u_user u2','mc.mc_send_user_id=u2.user_id','LEFT')
            ->join('up_shops s','c.coupon_s_id=s.s_id','LEFT')
            ->join('up_area a','s.s_sheng=a.district_id','LEFT')
            ->join('up_area a2','s.s_shi=a2.district_id','LEFT')
            ->join('up_area a3','s.s_qu=a3.district_id','LEFT')
            ->where($where)
            ->field($field)
            ->find();
        $today = date('Y-m-d');
        if($today > $data['mc_over_date']){
            $data['coupon_use_day2'] = '已过期';
        }else{
            $data['coupon_use_day2'] = $this->daysByTwoDate($today,$data['mc_over_date']);
        }

        return json(['status'=>200,'msg'=>$data]);
    }
    public function daysByTwoDate($start,$end)
    {
        $datetime_start = date_create($start);
        $datetime_end = date_create($end);
        $days = date_diff($datetime_start, $datetime_end);
        return $days->days;
    }
    /**
     * 点击领取
     */
    public function receiveCoupon(){
        extract(input());
        $where = array();
        $where['mc_id'] = $mc_id;
        //1、列表
        $res = Db::table('up_my_shop_coupon')->where($where)->update([
            'mc_send_status'=>3,
            'mc_take_time'=>date('Y-m-d H:i:s')
        ]);
        if($res){
            return json(['status'=>200,'msg'=>'ok']);
        }else{
            return json(['status'=>0,'msg'=>'操作失败']);
        }
    }
    /**
     * 送人之前找人
     */
    public function findUser(){
        extract(input());
        $where = array();
        $where['user_phone'] = $phone;
        //1、列表
        $res = Db::table('up_u_user')->where($where)->field('user_phone,user_id')->find();
        if($res){
            if($res['user_id'] == $user_id){
                return json(['status'=>0,'msg'=>'不能送给自己']);
            }
            return json(['status'=>200,'msg'=>$res]);
        }else{
            return json(['status'=>0,'msg'=>'查无此人']);
        }
    }
    /**
     * 点击送人
     */
    public function giveCoupon(){
        extract(input());
        $where = array();
        $where['mc_id'] = $mc_id;
        if($who == $user_id){
            return json(['status'=>0,'msg'=>'不能送给自己']);
        }
        $can = Db::table('up_my_shop_coupon')->where($where)->field('mc_send,mc_user_id')->find();
        if($can['mc_send'] != 1){
            return json(['status'=>0,'msg'=>'此券已经送人']);
        }
        if($can['mc_user_id'] != $user_id){
            return json(['status'=>0,'msg'=>'这不是你的券，你不能送人']);
        }
        //1、列表
        $res = Db::table('up_my_shop_coupon')->where($where)->update([
            'mc_send'=>2,
            'mc_send_status'=>2,
            'mc_send_user_id'=>$who,
            'mc_send_time'=>date('Y-m-d H:i:s')
        ]);
        if($res){
            return json(['status'=>200,'msg'=>'ok']);
        }else{
            return json(['status'=>0,'msg'=>'操作失败']);
        }
    }
    public function getMyNum($unique_no,$coupon_s_id){
        $num = Db::table('up_my_shop_coupon')
            ->where('mc_code',$unique_no)
            ->where('mc_s_id',$coupon_s_id)
            ->find();
        if($num){
            $unique_no = substr(base_convert(md5(uniqid(md5(microtime(true)),true)), 16, 10), 0, 8);
            return $this->getMyNum($unique_no,$coupon_s_id);
        }else{
            return $unique_no;
        }

    }

}